<?php
/**
 * @author GhostWei
 * @date Oct 14, 2012
 */
class resource_api_advertise extends resource_api_abstract {
	
	public static function create($src, $rigorous = true) {
		if(empty($src)) {
			throw new resource_exception("advertisement image/flash/video.. is empty.");
		}
		$content = file_get_contents($src['tmp_name']);
		if(!$content) {
			throw new resource_exception("advertisement image/flash/video.. is empty.");
		}
		$pathinfo = pathinfo($src['name']);
		$ext = strtolower($pathinfo['extension']);
		$filter = resource_config_advertise::getExtensions();
		if(empty($ext) || !in_array($ext, $filter)) {
			throw new resource_exception("advertisement image/flash/video.. type is not suppoted,it should be a(n) '" . implode(',', $filter) . "' file.");
		}
		$md5 = system_file_io::md5Filename(null, $content);
		$md5code = resource_config_advertise::md5Path($md5);
		$md5file = resource_config_advertise::dir() . $md5code;
		$md5name = '/original.' . $ext;
		if(!file_exists($md5file . $md5name)) {
			system_file_io::mkdir($md5file);
			if(!file_put_contents($md5file . $md5name, $content)) {
				throw new resource_exception("Save file faild,Please check if the folder is writable.");
			}
		}
		try {
			$row = self::saveToDatabase(array(
					'hash' => $md5, 
					'size' => $src['size'], 
					'ext' => $ext, 
					'dimension' => array('width' => 0, 'height' => 0)
				));
			return $row;
		} catch (Exception $ex) {
			if(!parent::$_isInDtabase) {
				@unlink($md5file . $md5name);
			}
			throw $ex;
		}
	}

}
